#==================================================
#	Root
#==================================================
# 根节点
#==================================================
# @datetime: 2021-12-11 20:06:09
#==================================================

extends "res://addons/function_tree/src/Core.gd"


## 初始化完成
signal init_finished


const Blackboard = preload("res://addons/function_tree/src/base/Blackboard.gd")
const Property = Blackboard.Property
const Enabled = Blackboard.Enabled


var property : Property


var __child_list := []



#==================================================
#   Set/Get
#==================================================
func get_property() -> Property:
	return blackboard.property



#==================================================
#   内置方法
#==================================================
func _ready():
	self.root = self
	self.host = get_parent()
	self.blackboard = Blackboard.new()
	self.blackboard.init_blackboard(self)
	property = blackboard.property
	
	# 遍历所有节点,设置基本属性
	__child_list = foreach_child(self)
	
	for child in __child_list:
		child.root = self
		child.host = self.host
		child.blackboard = self.blackboard
		# 子节点线程都设为停止，节省资源
		child.set_process(false)
		child.set_physics_process(false)
	self.pause_mode = Node.PAUSE_MODE_INHERIT
	
	# 初始化数据
	for child in __child_list:
		child._init_data()
	# 初始化节点
	for child in __child_list:
		child._init_node()
	# 初始化完成
	for child in __child_list:
		child._init_finish()
	
	emit_signal("init_finished")


func _physics_process(delta):
	# 接收输入
	for child in __child_list:
		child._process_input(delta)
	# 执行功能
	for child in __child_list:
		child._process_execute(delta)
	# 完成
	for child in __child_list:
		child._process_finish(delta)



#==================================================
#   节点初始化
#==================================================
##  遍历子节点
## @node  要遍历的节点
func foreach_child(node: Node, arr := []) -> Array:
	for child in node.get_children():
		if is_function_node(child):
			arr.push_back(child)
	for child in node.get_children():
		foreach_child(child, arr)
	return arr


